/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.mzk.kramerius.rukopisy.tools.linksCorrection;

import cz.mzk.kramerius.rukopisyimport.sourceData.SourceDocumentsManager;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Martin Řehánek (rehan at mzk.cz)
 */
public class LinksCorrector {

    //napr. /home/rehan/rukopisy/ENRICH
    private final File rootDocumentDir;

    public LinksCorrector(File rootDocumentDir) {
        this.rootDocumentDir = rootDocumentDir;
    }

    public void repairAllDirsInRootDir() {
        for (File file : rootDocumentDir.listFiles()) {
            if (file.isDirectory()) {
                String docDirName = file.getName();
                File documentDir = buildSubdirFile(rootDocumentDir, docDirName);
                File logFile = buildLogFile(rootDocumentDir, docDirName);
                repairDir(documentDir, logFile);
            }
        }
    }

    private File buildLogFile(File logDir, String docDirName) {
        String filename = logDir.getAbsolutePath() + File.separator + docDirName + "-oprava_linku.log.txt";
        return new File(filename);
    }

    private File buildSubdirFile(File logDir, String docDirName) {
        String filename = logDir.getAbsolutePath() + File.separator + docDirName;
        return new File(filename);
    }

    public void repairSubdir(String docDirName) {
        File documentDir = buildSubdirFile(rootDocumentDir, docDirName);
        File logFile = buildLogFile(documentDir, docDirName);
        repairDir(documentDir, logFile);
    }

    private void repairDir(File documentDir, File logFile) {
        PrintStream out = null;
        try {
            out = new PrintStream(logFile);
            SourceDocumentsManager manager = new SourceDocumentsManager(documentDir, null);
            System.err.println("digitalized files:" + manager.getDigitizedFiles().size());
            for (File digitizedTeiFile : manager.getDigitizedFiles()) {
                out.println();
                out.println("===============================");
                out.println("soubor " + digitizedTeiFile.getName());
                //File digitizedTeiFile = new File("/home/rehan/rukopisy/ENRICH/Moll_Rkp/Moll-RKP-0090.900,27.tei.xml");
                TeiToRepair teiToRepair = new TeiToRepair(digitizedTeiFile, out);
                teiToRepair.repair();
            }
            out.println("===============================");
        } catch (FileNotFoundException ex) {
            Logger.getLogger(LinksCorrector.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            out.close();
        }
    }
}
